//
//  RCRecommendFoodListViewController.m
//  RocketProject
//
//  Created by Wu Chengwei on 13-9-21.
//  Copyright (c) 2013年 Rocket. All rights reserved.
//

#import "RCRecommendFoodListViewController.h"
#import "RCSelectorView.h"
#import "MileSeletor.h"
#import "GloableEngineService.h"
#import "RCRecommendFoodTypeView.h"
#import "UIColor-Expanded.h"
#import "NSString+NSString_Ex_.h"
#import "CommonDefines.h"
#import "MBProgressHUD.h"
#import "RCRecommendFoodListDataModel.h"
#import "RCRecommendFoodNewCell.h"
#import "NSArray+EX.h"
#import "RCRecommendFoodDetailViewController.h"

#define kRCCategoryView_Distrcit 80
#define kRCCategoryView_Category 81

#define kBottomImageFile           @"image_merchant_street.png"

@interface RCRecommendFoodListViewController ()<IManagerDelegate,RCSeletorViewDelegate,MileSeletorDelegate,RCSubViewTablelistProtocol,RCRecommendFoodTypeViewDelegate,MBProgressHUDDelegate>{
    
    
    int64_t                 _foodTypeReqID, _listReqID;
    
    RCRecommendAllFoodListDataModel *_dataModel;
    RCRecommendFoodTypeDataModel *_foodTypeDataModel;
    
    BOOL                     isRefresh;
    
    
    RCSelectorView           *_selectorView;
    
    //请求参数
    NSInteger                _reqMerchantDistance;  //商户距离
    NSString                 *_reqFoodType;       //美食类型id

    kMerchantsSortedType     _reqSortedType;        //排序类型
    
    NSArray                 *_distanceArray;
    NSDictionary            *_merchantTypeDic;
    NSArray                 *_sortedArray;
    
    NSInteger               _pn;
    
}
@property (nonatomic, retain) RCRecommendAllFoodListDataModel *dataModel;
@property (nonatomic, retain) RCRecommendFoodTypeDataModel *foodTypeDataModel;
@property (nonatomic, assign) NSString *reqFoodType;
@property (nonatomic, retain) MBProgressHUDEx *progressHub;
@property (nonatomic, retain) NSMutableArray *tableDataArray;

@end

@implementation RCRecommendFoodListViewController

@synthesize dataModel = _dataModel;
@synthesize foodTypeDataModel = _foodTypeDataModel;
@synthesize reqFoodType  = _reqFoodType;
@synthesize progressHub = _progressHub;
@synthesize tableDataArray = _tableDataArray;


-(id)init{
    self = [super init];
    if (self) {
        
        _reqMerchantDistance = 0; //默认1000m
        _reqSortedType       = kSortedType_Default;
        _reqFoodType         = @"food";
                
        _distanceArray = [[NSArray alloc] initWithObjects:@"500m",@"5km",@"10km",@"不限距离", nil];
        _sortedArray   = [[NSArray alloc] initWithObjects:@"默认排序",@"费用从低到高排序",@"按距离排序", nil];
        _tableDataArray = [[NSMutableArray alloc]initWithCapacity:10];
    }
    return self;
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[IManager sharedInstance] cancelFetchDataRequestByRequestID:_foodTypeReqID];
    [[IManager sharedInstance] cancelFetchDataRequestByRequestID:_listReqID];
}

- (void) dealloc
{
    
    [[IManager sharedInstance] cancelFetchDataRequestByRequestID:_foodTypeReqID];
    [[IManager sharedInstance] cancelFetchDataRequestByRequestID:_listReqID];
    
    [_merchantTypeDic   release];
    [_distanceArray     release];
    [_sortedArray       release];
    [_reqFoodType   release];
    self.progressHub.delegate = nil;
    self.progressHub = nil;
    self.foodTypeDataModel = nil;
    self.tableDataArray = nil;
    [super dealloc];
    
}

-(void)loadView{
    [super loadView];
    self.titleLabelText = @"全部美食";
    self.navigationItem.titleView = [self createTitleView];
}


- (void)viewDidLoad
{
    
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    
    [self refreshData];
    [self getTypeCatogory];
    
    NSArray *titleArray = [NSArray arrayWithObjects:@"500m",@"美食",@"默认排序", nil];
    
    _selectorView = [[RCSelectorView alloc] initWithFrame:CGRectMake(0, 0, 320, 50) titleArray:titleArray];
    _selectorView.delegate = self;
    [self.view addSubview:_selectorView];
    [_selectorView setBackgroundColor:[UIColor clearColor]];
    [_selectorView release];
    
    
    // 设置tableview相关参数
    if ( baseVCTableView != nil ) {
        self.view.autoresizingMask |= UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleBottomMargin;
        baseVCTableView.autoresizingMask |= UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleBottomMargin;
        baseVCTableView.backgroundColor = [UIColor clearColor];
        baseVCTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        baseVCTableView.frame = self.view.bounds;
        CGRect tableViewNewFrame = CGRectMake(baseVCTableView.frame.origin.x,baseVCTableView.frame.origin.y+50,baseVCTableView.frame.size.width,baseVCTableView.frame.size.height-self.navigationController.navigationBar.frame.size.height-4);
        baseVCTableView.frame = tableViewNewFrame;
        baseVCTableView.tableHeaderView = nil;
        baseVCTableView.tableFooterView = nil;
        [self addPullRefresh];
    }
    
    
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma
#pragma mark Get Category Or District Tags

- (void) getTypeCatogory
{
//    NSString *cityID = [[GloableEngineService sharedInstance] selectedCityID];
    _foodTypeReqID = [[IManager sharedInstance]requestFoodTypeList:self];
}



#pragma
#pragma mark IManage Delegate
-(void) updateViewForSuccess:(IDataModel *)dataModel withRequestId:(int64_t)requestId
{
    
    if ([dataModel isKindOfClass:[RCRecommendAllFoodListDataModel class]]) {
        
        [_progressHub removeFromSuperview];
        [_progressHub release];
        _progressHub = nil;
        
        if (isRefresh) {
            //下拉刷新
            self.dataModel = (RCRecommendAllFoodListDataModel *)dataModel;
            [_tableDataArray removeAllObjects];
            [_tableDataArray addObjectsFromArray:self.dataModel.itemListArray];
            [self finishRefreshingData];
        }else{
            //加载更多的
            RCRecommendAllFoodListDataModel *newData = (RCRecommendAllFoodListDataModel *)dataModel;
            self.dataModel.pn = newData.pn;
            self.dataModel.rn = newData.rn;
            self.dataModel.total = newData.total;
            [_tableDataArray addObjectsFromArray:newData.itemListArray];
            
            [baseVCTableView reloadData];
            [self finishLoadMoreData];
        }
        
        NSInteger currentTotal = [_tableDataArray count];
        _pn = currentTotal;
        if (currentTotal < self.dataModel.total) {
            [self addPullLoadMore];
        }else{
            [self noMoreData];
        }
    }else{
        //category分类数据
        RCRecommendFoodTypeDataModel *typesModel = (RCRecommendFoodTypeDataModel*)dataModel;
        self.foodTypeDataModel = typesModel;
        RCRecommendFoodTypeItem *item = [self.foodTypeDataModel.typeItemList safeObjectAtIndex:0];
        _selectorView.selectedIndex = 1;
        [_selectorView changeCurrentTabbarTitle:item.typeName];
    }
    
}


-(void) updateViewForError:(NSError *)errorInfo withRequestId:(int64_t)requestId
{
    if (_listReqID == requestId) {
        [_progressHub removeFromSuperview];
        [_progressHub release];
        _progressHub = nil;
        
        if (isRefresh) {
            //下拉刷新

            [self finishRefreshingData];
        }else{
            //加载更多的
            [self finishLoadMoreData];
        }
    }
}


-(void) loadMoreData
{
    isRefresh = NO;
    NSString *cityID = [[GloableEngineService sharedInstance] selectedCityID];
    
    _listReqID = [[IManager sharedInstance]requestFoodListInfo:cityID withFoodType:_reqFoodType withPn:_pn withDistance:_reqMerchantDistance withSoretedType:_reqSortedType withDelegate:self];
    
}

#pragma
#pragma mark ServerData ----下拉刷新数据

-(void) refreshData
{
    _progressHub = [[MBProgressHUDEx alloc] initWithView:self.view
                                               TopHeight:0
                                        withBottomHeight:0
                                           withLeftWidth:0
                                          withRightWidth:0
                                    withExclusiveObjects:nil];
    _progressHub.delegate = self;
    _progressHub.labelText = @"加载中...";
    [self.view addSubview:_progressHub];
    [self.view bringSubviewToFront:_progressHub];
    [_progressHub show:YES];
    isRefresh = YES;
    NSString *cityID = [[GloableEngineService sharedInstance] selectedCityID];
    
    _pn = 0;
    
    _listReqID = [[IManager sharedInstance]requestFoodListInfo:cityID withFoodType:_reqFoodType withPn:0 withDistance:_reqMerchantDistance withSoretedType:_reqSortedType withDelegate:self];
    
}



#pragma
#pragma mark SubView Delegate Start


#pragma mark SubView Delegate------SubViews

-(UIView *)viewForSelectorIndex:(NSInteger)index
{
    if (index == 0) {
        
        MileSeletor  *_mileSeletorView = [[[MileSeletor alloc] initWithFrame:CGRectMake(0, 0, 320, 50) andDataSource:_distanceArray] autorelease];
        _mileSeletorView.delegate = self;
        [_mileSeletorView setBackgroundColor:[UIColor whiteColor]];
        return _mileSeletorView;
        
    }else if (index == 1) {
        
        RCRecommendFoodTypeView *foodTypeView = [[[RCRecommendFoodTypeView alloc]initWithFrame:CGRectMake(0, 0, 320, UIScreenHeight-64-50-20) andDataSource:self.foodTypeDataModel]autorelease];
        foodTypeView.delegate = self;
        
        return foodTypeView;
        
    }else {
        RCSubViewTablelist *v = [[[RCSubViewTablelist alloc]
                                  initWithFrame:CGRectMake(0, 0, 320, 120)
                                  andTitles:_sortedArray] autorelease];
        v.delegate = self;
        return v;
    }
}



#pragma mark SubView Delegate------SubView Delegate  1

- (void) didSelectMileSeletorAtIndex:(NSInteger)index
{
    NSString *distance = [_distanceArray objectAtIndex:index];
    [_selectorView changeCurrentTabbarTitle:distance];
    [_selectorView selectorHide];
    
    NSRange kmRang = [distance rangeOfString:@"km"];
    NSRange rang;
    NSRange noLimitRange;
    
    if (kmRang.location == NSNotFound) {
        rang = [distance rangeOfString:@"m"];
        if (rang.location != NSNotFound) {
            _reqMerchantDistance = [[distance substringToIndex:rang.location] intValue];
            [self refreshData];
        }
        
        noLimitRange = [distance rangeOfString:@"不限距离"];
        if (noLimitRange.location != NSNotFound) {
            _reqMerchantDistance = 0;
            [self refreshData];
        }
    }else{
        _reqMerchantDistance = [[distance substringToIndex:kmRang.location] intValue]*1000;
        [self refreshData];
    }
    
    
}


#pragma mark SubView Delegate------SubView Delegate  2

-(void)selectFoodTypeItem:(RCRecommendFoodTypeItem *)item{
    [_selectorView changeCurrentTabbarTitle:item.typeName];
    [_selectorView selectorHide];
    
    self.reqFoodType  = item.typeID;
    
    [self refreshData];
}




#pragma mark SubView Delegate------SubView Delegate  3

- (void) rcSubViewTablelist:(RCSubViewTablelist *)rcSubViewTablelist didSelectTitle:(NSString *)titleTag atIndex:(NSInteger)index
{
    [_selectorView changeCurrentTabbarTitle:titleTag];
    [_selectorView selectorHide];
    
    _reqSortedType = index;
    
    [self refreshData];
}


#pragma mark SubView Delegate End



#pragma
#pragma mark TableView DataSource & Delegate

-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 94;
}

-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_tableDataArray count];
}

-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellID = @"RCRecommendFoodListCell";
    RCRecommendFoodNewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil) {
        cell = [[[RCRecommendFoodNewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID] autorelease];
    }
    RCRecommendFoodListItem *item = [_tableDataArray safeObjectAtIndex:[indexPath row]];
    if (nil == item) {
        return nil;
    }
    
    [cell bindData:item];
    return cell;
}


-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
//    RCMerchant *merchant = [self.dataModel.listItems objectAtIndex:[indexPath row]];
//    
//    RCMerchantDetailVC *detail = [[RCMerchantDetailVC alloc] initWithMerchantID:merchant.merchantID];
//    [self.navigationController pushViewController:detail animated:YES];
//    [detail release];
    RCRecommendFoodListItem *food = [self.dataModel.itemListArray safeObjectAtIndex:[indexPath row]];
    RCRecommendFoodDetailViewController *vc = [[RCRecommendFoodDetailViewController alloc]initWithFoodID:food.foodID];
    [self.navigationController pushViewController:vc animated:YES];
    [vc release];
}

@end
